#include <stdio.h>                                                                        
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>


//child -> write ; father -> read
int main()
{
  int fd[2] = { 0 };
  if (pipe(fd) < 0){ //使用pipe创建匿名管道
    perror("pipe");
    return 1;
  }

  pid_t id = fork();
  if (id == 0){ //child

    close(fd[0]); //子进程关闭读端
    
    //子进程向管道写入数据
    const char* buf = "hello father, I am child...";
    int count = 5;
    while (count--){
      write(fd[1], buf, strlen(buf));
      sleep(1); 
    }
    close(fd[1]); 
    exit(0);//写完数据子进程退出
  }                                                                                       

  //father
  close(fd[1]); //父进程关闭写端


  char buff[64];
  while (1){
    ssize_t s = read(fd[0], buff, sizeof(buff));
    if (s > 0){
      buff[s] = '\0'; 
      printf("child send to father:%s\n", buff);
    }
    else if (s == 0){
      printf("read file end\n");
      break;
    }
    else{
      printf("read error\n");
      break;                                                                              
    }
  }

  close(fd[0]); //父进程读取完毕，关闭文件
  waitpid(id, NULL, 0);//等待子进程
  return 0;
}
